import { RequestConfig, requestHead, LOCAL_STORAGE_NAME } from "@/common/globalConfig";
import { errorTips, statusCodes } from "./requestCode";
import { zalert, toast } from "@/utils/util";
const { success_code, login_failure_code, register_code } = statusCodes;

let flag = true; //记录当前是否要提示错误信息
type RequestOptionsMethod =
  | "OPTIONS"
  | "GET"
  | "HEAD"
  | "POST"
  | "PUT"
  | "DELETE"
  | "TRACE"
  | "CONNECT";

interface baseConfig {
  url: string;
  method: RequestOptionsMethod;
  header?: any;
  data?: Record<string, any>;
  params?: Record<string, any>;
  showLoading?: boolean | string; //是否显示loading，字符串类型时loading的title会设置成该字符串
}
export interface CustomSuccessData<T = any> {
  code: number | string;
  msg?: string;
  message?: string;
  data?: T;
  [keys: string]: any;
}
// 验证登录情况登录失效跳转到登录页面;
function ajaxFilter(data: CustomSuccessData) {
  let status = true;
  if (data.code == "00010" || data.code == "00011") {
    status = false;
    // zalert('登录状态失效', () => {
    //     uni.reLaunch({
    //         url: '/pages/login/login'
    //     });
    // });
  }
  return status;
}
// 每次调用接口后需要重新刷新token 防止接口频繁登录失效
function refreshToken(toke: string) {
  if (!toke) return;
  // if (userInfo.token && userInfo.token.length > 0) {
  //     userInfo.setToken(toke);
  // }
  uni.setStorageSync(LOCAL_STORAGE_NAME.TOKEN, toke);
}
/**
 * 发送请求
 */
const baseRequest = <T>(config: baseConfig) => {
  if (config.showLoading) {
    uni.showLoading({
      title: typeof config.showLoading == "string" ? config.showLoading : "加载中",
      mask: true
    });
  }
  if (config.method === "GET" && config.params) {
    let url = config.url + "?";
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      const part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof value !== "undefined") {
        if (typeof value === "object") {
          for (const key of Object.keys(value)) {
            const params = propName + "[" + key + "]";
            const subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  const myUrl = RequestConfig.BASE_URL + config.url;
  config.header = config.header || {};
  config.header.token =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwicGFzc3dvcmQiOiIiLCJuaWNrbmFtZSI6IuaIkeaYr-iwgSIsInVzZXJfcGljIjoiaHR0cHM6Ly9jZG4udXZpZXd1aS5jb20vdXZpZXcvYWxidW0vMS5qcGciLCJzZXgiOiLmnKrnn6XmgKfliKsiLCJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzEwOTAzMTU4LCJleHAiOjE3MTA5MzkxNTh9.mLrMgmVPRFZxCpiQ-iCMCy_RxkDs71wUDsBRkVoqheg";
  config.header = Object.assign(config.header, requestHead); //处理请求头
  return new Promise<CustomSuccessData<T>>((reslove, reject) => {
    uni.request({
      url: myUrl,
      method: config.method || "GET",
      header: config.header,
      data: config.data || {},
      timeout: 30000,
      success: (res: any) => {
        closeLoading(config.showLoading);
        if (ajaxFilter(res.data) && res.statusCode == 200) {
          refreshToken(res.header["AT-TOKEN"]);
          const data = res.data;
          const code = data.code || Number(success_code);
          if (code == success_code || register_code.includes(code)) {
            flag = true;
            return reslove(data);
          } else if (login_failure_code.includes(code)) {
            if (flag) {
              // err(data.msg);
            }
            //清空token和openId
            // useUserInfo().removeInfoMessage();
            reject(data);
          } else {
            if (flag) {
              toast(data.msg, true);
            }
            reject(data);
          }
        } else if (res.statusCode != 401) {
          reject(res.data);
        }
      },
      fail: (res: any) => {
        closeLoading(config.showLoading);
        if (res.msg && res.msg.indexOf("timeout") !== -1) {
          zalert("请求超时，请稍后再试");
        } else if (res.msg && res.msg.indexOf("request") !== -1) {
          zalert("服务器已关闭");
        } else {
          zalert("请求失败，请检查网络");
        }
        reject(res);
      }
    });
  });
};

function closeLoading(isClose: boolean | string) {
  if (isClose) {
    uni.hideLoading();
  }
}
export default baseRequest;
